import 'package:flutter/material.dart';
import 'package:flutter_project/common/route_page/route_name.dart';
import 'package:flutter_project/common/utils/screen_size_utils.dart';
import 'package:flutter_project/config/app_bar_view.dart';
import 'package:flutter_project/config/common_string_config.dart';
import 'package:flutter_project/config/empty_img_view.dart';
import 'package:flutter_project/config/loading_toast.dart';
import 'package:flutter_project/config/theme_color.dart';
import 'package:flutter_project/home/home_video_details_model.dart';
import '../add_publish/pic_video_common_utils.dart';
import '../add_publish/publish_add_main_page.dart';
import '../common/utils/asset_img_utils.dart';
import '../common/utils/photo_view_utils.dart';
import '../requst/dio_http_utils.dart';
import '../video/video_player_view.dart';

class HomeVideoDetailsPage extends StatefulWidget {
  final int id;
  final int type;
  final bool isFromDetails;

  const HomeVideoDetailsPage(
      {required this.id, this.type = 1, this.isFromDetails = false, super.key});

  @override
  State<HomeVideoDetailsPage> createState() => _HomeVideoDetailsPageState();
}

class _HomeVideoDetailsPageState extends State<HomeVideoDetailsPage> {
  VideoDetailsRespModel itemDetailModel = VideoDetailsRespModel();
  ValueNotifier<int> likeInt = ValueNotifier<int>(0);
  String videoOriginalUrl = '';
  String imgOriginalUrl = '';
  String rateStr = '';

  @override
  Widget build(BuildContext context) {
    return CommonAppWidget.navAppBar(
      title: widget.isFromDetails ? '创作结果' : '详情',
      rightActions: [
        TextButton(
            onPressed: () {
              toast('举报成功');
            },
            child: Text(
              '举报',
              style: TextStyle(fontSize: 14, color: ThemeColor.textColor3),
            )),
      ],
      childWidget: Column(
        children: [
          Expanded(
            child: ListView(
              children: [
                (widget.type == 1 && itemDetailModel.url.isNotEmpty)
                    ? VideoPlayerView(
                        path: itemDetailModel.url,
                      )
                    : EmptyImgView.commonEmptyImg(
                        url: itemDetailModel.url,
                        imgWidth:
                            ScreenSizeUtils.deviceScreenWidth(context) - 40,
                        imgHeight: 181),
                getItemView(
                    leftName: '提示词', rightName: itemDetailModel.prompt ?? ''),
                getItemView(
                    leftName: '负向提示词',
                    rightName: itemDetailModel.negativePrompt ?? ''),
                getItemView(
                    leftName: '随机种子',
                    rightName: (itemDetailModel.seed ?? 0).toString()),
                getItemView(leftName: '长宽比', rightName: rateStr),
                getItemView(
                    leftName: '内容类型',
                    rightName: widget.type == 1 ? '视频' : '图片'),
                getItemView(
                    leftName: '来源',
                    rightName: '',
                    childWidget: getSourceWidget()),
              ],
            ),
          ),
          Column(
            children: [
              Container(
                height: 0.5,
                color: ThemeColor.lineColor,
              ),
              widget.isFromDetails
                  ? Visibility(
                      visible: itemDetailModel.url.isNotEmpty,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          PicVideoCommonUtils.getBottomViewBtn(
                            name: '保存到相册',
                            tapAction: () {
                              String fileUrl = itemDetailModel.url;
                              if (PicVideoCommonUtils.isPictrueConetent(
                                  fileUrl)) {
                                AssetImgUtils.downloadImgToAlbum(fileUrl);
                              } else {
                                AssetImgUtils.downloadVideoToAlbum(fileUrl);
                              }
                            },
                          ),
                        ],
                      ),
                    )
                  : Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Visibility(
                          visible: (widget.type == 1) &&
                              (itemDetailModel.authorNickname !=
                                  CommonStringConfig.nickName),
                          child: ValueListenableBuilder(
                              valueListenable: likeInt,
                              builder: (BuildContext context, int value,
                                  Widget? child) {
                                return GestureDetector(
                                  onTap: () {
                                    clickLikeAndUnLikeAction();
                                  },
                                  child: Container(
                                    color: ThemeColor.mainBgColor,
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        Icon(
                                          Icons.favorite,
                                          color: value == 1
                                              ? Colors.red
                                              : ThemeColor.textColorSecond,
                                        ),
                                        const SizedBox(
                                          width: 10,
                                        ),
                                        Text(
                                            (itemDetailModel.likes).toString()),
                                        const SizedBox(
                                          width: 10,
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              }),
                        ),
                        const SizedBox(
                          width: 10,
                        ),
                        PicVideoCommonUtils.getBottomViewBtn(
                            name: '再创作',
                            tapAction: () {
                              RouteNames.push(PublishAddMainPage(
                                isFromDetail: true,
                                itemDetailModel: itemDetailModel,
                                type: widget.type,
                              ));
                            }),
                      ],
                    ),
            ],
          ),
        ],
      ),
    );
  }

  Widget getItemView(
      {String leftName = '', String rightName = '', Widget? childWidget}) {
    return Column(
      children: [
        const SizedBox(
          height: 12,
        ),
        Row(
          children: [
            const SizedBox(
              width: 20,
            ),
            SizedBox(
              width: 140,
              child: Text(
                leftName,
              ),
            ),
            Expanded(
              child: childWidget ??
                  Text(
                    rightName,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 2,
                  ),
            ),
          ],
        ),
        const SizedBox(
          height: 12,
        ),
        Container(
          color: ThemeColor.lineColor,
          height: 0.5,
        ),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    getDeTailsData();
  }

  getDeTailsData() async {
    Map<String, dynamic>? dataMap = {'MediaId': widget.id, 'Type': widget.type};
    var res =
        await HttpDioUtils.request('media/getMediaDetail', params: dataMap);
    VideoDetailsModel resModel = VideoDetailsModel.fromJson(res);
    itemDetailModel = resModel.resp ?? VideoDetailsRespModel();
    String widthHeight = '${itemDetailModel.width}x${itemDetailModel.height}';
    rateStr = PicVideoCommonUtils.widthHeightMap()[widthHeight];
    itemDetailModel.rateStr = rateStr;
    if (res != null && res is Map) {
      Map resMap = res['Resp'];
      if (resMap['StyleImgs'] != null) {
        Map videoMap = resMap['StyleImgs'];
        imgOriginalUrl = videoMap[videoMap.keys.first];
        itemDetailModel.imgOriginalUrl = imgOriginalUrl;
        itemDetailModel.fileId = videoMap.keys.first;
        debugPrint('图片来源$imgOriginalUrl');
      }

      if (resMap['OriginalVideo'] != null) {
        Map videoMap = resMap['OriginalVideo'];
        videoOriginalUrl = videoMap.values.first;
        itemDetailModel.videoOriginalUrl = videoOriginalUrl;
        itemDetailModel.fileId = videoMap.keys.first;
        debugPrint('视频来源$videoOriginalUrl');
      }
    }
    setState(() {});
  }

  void clickLikeAndUnLikeAction() async {
    String apiUrl = 'media/likeMedia';
    if (likeInt.value == 1) {
      apiUrl = 'media/unlikeMedia';
    }
    Map<String, dynamic>? dataMap = {
      'MediaId': itemDetailModel.id,
      'MediaType': 1,
    };
    var res = await HttpDioUtils.request(apiUrl, params: dataMap);
    if (res != null && res['ErrCode'] == 0) {
      if (likeInt.value == 0) {
        likeInt.value = 1;
      } else {
        likeInt.value = 0;
      }
      itemDetailModel.userLike = likeInt.value;
      if (likeInt.value == 1) {
        itemDetailModel.likes = (itemDetailModel.likes) + 1;
      } else {
        itemDetailModel.likes = (itemDetailModel.likes) - 1;
      }
      CommonStringConfig.likeEventBus.fire({"isRefreshHomePage": true});
      CommonStringConfig.likeEventBus.fire({"isRefreshCollectPage": true});
    }
  }

  getSourceWidget() {
    if (imgOriginalUrl.isNotEmpty) {
      return GestureDetector(
        onTap: (){
          RouteNames.push(PhotoPreview(
            galleryItems:[itemDetailModel.imgOriginalUrl],
            defaultImage: 0,
          ));
        },
        child: EmptyImgView.commonEmptyImg(
            url: imgOriginalUrl,
            imgWidth: ScreenSizeUtils.deviceScreenWidth(context) - 40,
            imgHeight: 181),
      );
    } else if (videoOriginalUrl.isNotEmpty) {
      return VideoPlayerView(
        path: videoOriginalUrl,
      );
    }
  }
}
